<?php
namespace Controllers;
use App;
use Config\Base as Config;
use DB\ArticleService;
use DB\FacebookService;
use DB\UserService;

/**
 * @author Evgeny Baranov <evgeny@baranov.eu>
 */
class Article extends Base {

    /**
     * @var \DB\ArticleService
     */
    protected $articleService;

    /**
     * @var \DB\UserService
     */
    protected $userService;

    /**
     * @var FacebookService
     */
    protected $facebookService;

    public function __construct() {
        $this->articleService = new ArticleService();
        $this->userService = new UserService();
        $this->facebookService = new FacebookService();
    }


    /**
     * @param array $param
     * @return array:
     */
    public function index(array $param) {
        $page = (count($param) > 0) && ($page = intval(array_shift($param))) ? $page : 1;
        $this->view = 'Article';
        $result = $this->articleService->getList($page, intval(Config::instance()->PAGE_SIZE), \Models\Article::GROUP_BLOG);
        return $result;
    }


    /**
     * @param array $param
     * @return array
     */
    public function view(array $param) {
        $path = array_shift($param);

        $from = isset($_GET['from']) ? $_GET['from'] : null;
        $this->setView('Article')->setTmpl('view.phtml');

        try {
            if (is_numeric($path)) {
                $article = $this->articleService->getById(intval($path), App::getLang());
                $article = array_shift($article);
            } else {
                $article = $this->articleService->findByRoute($path, $from);
            }
        } catch (\Exception $e) {
            \App::error(404);
            exit;
        }
        if ($article->getContent()->getPath() != $path) {
            $p = \Path::getInstance();
            \App::redirect($p->setCurrent($article->getContent()->getPath())->join('/'));
        }
        \App::setLang($article->getContent()->getLanguageCode());
        if ($from) {
            \App::redirect($article->getContent()->getPath());
        }
        \App::getDocument()->prependToTitle($article->getContent()->getTitle())
            ->addMetaOG('type', 'article')
            ->addMetaOG('title', $article->getContent()->getTitle())
            ->addMetaOG('description', strip_tags($article->getContent()->getAnnotation()));

        $this->articleService->log($article);

        // Prepare links for gallery
        $max_sz = 500;
        $max_icon_sz = 130;

        $x = $y = $max_sz;
        $ix = $iy = $max_icon_sz;

        if ($article->haveAlbum()) {
            $photos = $article->getAlbum()->getPhotos();
            foreach ($photos as $p) {
                $i = $p->getImage($max_sz);
                App::getDocument()->addMetaOG('image', $i->source);
                $x = min($x, $i->width);
                $y = min($y, $i->height);
                $t = $p->getIcon();
                $ix = min($ix, $t->width);
                $iy = min($iy, $t->height);
                $iy = $ix = min($ix, $iy);
            }
        }
        return array(
            'article' => $article,
            'gallery' => array(
                'x' => $x,
                'y' => $y,
                'ix' => $ix,
                'iy' => $iy,
                'max_sz' => $max_sz,
                'max_icon_sz' => $max_icon_sz
            )
        );
    }

    public function edit(array $param) {
        // TODO: move to admin controller
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to edit article.");
        }
        $id = intval(array_shift($param));
        $data = $this->articleService->getById($id);
        $this->setView('Article')->setTmpl('edit.phtml');

        if (count($data) < 1) {
            throw new \Exception("Article with id {$id} not found.");
        }
        $res = array();
        foreach (Config::instance()->lang->list as $l) {
            foreach ($data as $a) {
                if ($a->getContent()->getLanguageCode() == $l) {
                    $res[$l] = $a;
                    break;
                }
            }
            if (!isset($res[$l])) {
                $a = $data[0]->toArray();
                $a = array_merge($a, array(
                    'article_id' => $a['id'],
                    'language_code' => $l,
                    'path' => '',
                    'title' => '',
                    'content' => '',
                    'created' => '',
                    'updated' => ''
                ));
                $a = new \Models\Article($a);
                $res[$l] = $a;
            }
        }

        $back = isset($_GET['back']) ? $_GET['back'] : (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/');

        return array(
            'list' => $res,
            'back' => $back,
            'albums' => $this->facebookService->getPageAlbums()
        );
    }

    public function save(array $param) {
        $this->apply(array());
    }

    public function apply(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to edit article.");
        }

        $data = $_POST;
        $data['id'] = $data['article_id'];
        if (empty($data['path'])) {
            $data['path'] = $data['title'];
        }
        $data['path'] = mb_strtolower($data['path']);

        $data['path'] = trim(preg_replace('/[\s\.\:\;\?]+/', '_', $data['path']), '_');

        if ($data['id'] == 0) {
            $data['author'] = $user;
            $data['author_id'] = $user->getId();
        }

        if ($data['author_id'] && empty($data['author'])) {
            $data['author'] = $this->userService->getUser($data['author_id']);
        }

        if ($data['album_id'] && empty($data['album'])) {
            $data['album'] = $this->facebookService->getAlbum($data['album_id']);
        }

        $article = new \Models\Article($data);
        $article = $this->articleService->saveArticle($article);

        $this->jsonSuccess($article->toArray());
    }

    public function banner(array $param) {
        $id = intval(array_shift($param));

        $banner = $this->articleService->getAttachment($id);

        header('Content-type: ' . $banner->getMIME());

        echo $banner->getData();
        exit;
    }
}
